<template>
    <!--话术管理-->
    <div class="content_panel project_modules">
        <div class="content_panel project_modules">
            <div class="content_panel project_modules">
                <div class="content_panel_top">
                    <h3 class="panel_title">
                        <span>{{$t('salesManage.talkManage')}}</span>
                    </h3>
                    <el-form ref="form" :model="form" :rules="rules" :inline="false" class="module_form">
                        <el-row>
                            <el-col :span="5">
                                <!-- 模板名称 -->
                                <el-form-item prop="name">
                                    <el-input v-model="form.name" :placeholder="$t('salesManage.nameTemplate')" clearable></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-button @click="search" type="primary">{{ $t('common.search') }}</el-button>
                                <el-button @click="templateAdd" type="primary" class="search_panel_btn">{{$t('salesManage.templateAdd')}}</el-button>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
            </div>
        </div>

        <div class="module_content">
            <div class="content_panel project_modules">
                <div class="table_list">
                    <el-table :max-height="tableMaxHeight" :data="tableData" style="width: 100%;">
                        <!-- 编号 -->
                        <el-table-column prop="id" :label="$t('common.numbering')" min-width="110"></el-table-column>
                        <!-- 模板名称 -->
                        <el-table-column prop="name" :label="$t('salesManage.nameTemplate')" min-width="170"></el-table-column>
                        <!-- 问题数 -->
                        <el-table-column prop="number" :label="$t('salesManage.questionsNumber')" min-width="120"></el-table-column>
                        <!-- 模板说明 -->
                        <el-table-column prop="remark" :label="$t('salesManage.descriptionTemplate')" min-width="120">
                            <template slot-scope="scope">
                                <div class="edit_remark">
                                    <span v-if="!scope.row.remark || (scope.row.remark && scope.row.remark.length <= 7)">{{ scope.row.remark }}</span>
                                    <el-popover v-if="scope.row.remark && scope.row.remark.length > 7" trigger="hover" placement="top">
                                        <p class="popper-word-break">{{ scope.row.remark }}</p>
                                        <div slot="reference">
                                            <span v-if="scope.row.remark.length > 7">{{ scope.row.remark.substr(0, 7) }}...</span>
                                            <span v-else>{{ scope.row.remark }}</span>
                                        </div>
                                    </el-popover>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- 使用批次 -->
                        <el-table-column prop="useBatch" :label="$t('salesManage.batchUse')" width="200" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <div class="edit_remark">
                                    <span v-if="!scope.row.useBatch || (scope.row.useBatch && scope.row.useBatch.length <= 17)">{{ scope.row.useBatch }}</span>
                                    <el-popover v-if="scope.row.useBatch && scope.row.useBatch.length > 17" trigger="hover" placement="top">
                                        <p class="popper-word-break">{{ scope.row.useBatch }}</p>
                                        <div slot="reference">
                                            <span v-if="scope.row.useBatch.length > 17">{{ scope.row.useBatch.substr(0, 17) }}...</span>
                                            <span v-else>{{ scope.row.useBatch }}</span>
                                        </div>
                                    </el-popover>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- 最近一次编辑 -->
                        <el-table-column prop="updateTime" :label="$t('salesManage.editLast')" min-width="160">
                            <template slot-scope="scope">{{ scope.row.updateTime | formatDate('yyyy-MM-dd hh:mm:ss') }}</template>
                        </el-table-column>
                        <!-- 操作 -->
                        <el-table-column prop="waitHandleCount" :label="$t('common.operation')" min-width="330">
                            <template slot-scope="{ row }">
                                <!-- 0 待分配  1 已分配  2 已回收 -->
                                <!-- 编辑话术 -->
                                <el-button type="text" @click="editingTemplate(row)">{{$t('finance.edit')}}</el-button>
                                <!-- 删除 -->
                                <el-button type="text" @click="deleteTemplate(row)" class="btn_red">{{$t('system.delete')}}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页组件 -->
                    <pagination @pageChange="pageChange" :page="page"></pagination>
                </div>
            </div>
        </div>

        <!-- 编辑话术弹窗start -->
        <!-- :before-close="handleClose" -->
        <!-- 编辑话术 -->
        <!--params.questionnaireTemplate = this.templateEditForm.questionnaireTemplate;-->
        <!--params.questionList = this.editingStatementObj.list;-->
        <el-dialog :title="$t('salesManage.templateEdit')" :visible.sync="alertDialogVisible.templateEdit" width="500px">
            <div>
                <el-form :model="templateEditForm" :rules="templateEditFormRules" ref="templateEditForm" label-width="120px" class="demo-ruleForm" size="mini">
                    <el-form-item :label="$t('common.numbering')+':'" :label-width="formLabelWidth">{{templateEditForm.questionnaireTemplate.id}}</el-form-item>
                    <el-form-item :label="$t('salesManage.nameTemplate')+':'" :label-width="formLabelWidth" prop="questionnaireTemplate.name">
                        <el-input v-model="templateEditForm.questionnaireTemplate.name" auto-complete="off" :placeholder="$t('verify.plsInput')"></el-input>
                    </el-form-item>
                    <el-form-item :label="$t('salesManage.descriptionTemplate')+':'" :label-width="formLabelWidth" prop="remark">
                        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" :placeholder="$t('verify.underXWords',{x: 200})" v-model="templateEditForm.questionnaireTemplate.remark" :maxlength="200">
                        </el-input>
                    </el-form-item>
                    <el-form-item :label="$t('salesManage.plsQuestionType')+':'" :label-width="formLabelWidth">
                        <!-- 单选 多选 输入 -->
                        <el-button type="text" @click="addEditState(1)" size="medium" style="paddingTop:7px">{{$t('salesManage.singleChoice')}}</el-button>
                        <el-button type="text" @click="addEditState(2)" size="medium" style="paddingTop:7px">{{$t('salesManage.multipleSelection')}}</el-button>
                        <el-button type="text" @click="addEditState(3)" size="medium" style="paddingTop:7px">{{$t('salesManage.input')}}</el-button>
                    </el-form-item>

                    <!-- 编辑话术问题块start -->
                    <div class="editingStatement" ref="editingStatementWrap">
                        <div v-for="(itemBlock,indexBlock) in editingStatementObj.list" :key="indexBlock" class="editingStatementBlock">
                            <i class="el-icon-close icon-close" @click="deleteOptionBlock(indexBlock)"></i>
                            <!-- 【单选】start -->
                            <div v-if="itemBlock.questionType==1">
                                <el-form-item :label="'【'+$t('salesManage.singleChoice')+'】'" :label-width="formLabelWidth">
                                    <el-radio-group v-model="itemBlock.isMust">
                                        <!-- 必填 -->
                                        <el-radio :label="1">{{$t('salesManage.required')}}</el-radio>
                                        <!-- 选填 -->
                                        <el-radio :label="2">{{$t('salesManage.optional')}}</el-radio>
                                    </el-radio-group>
                                </el-form-item>

                                <el-row>
                                    <el-col :span="20">
                                        <!-- 问题 -->
                                        <el-form-item :label="$t('salesManage.problem')" class="is-required" >
                                            <el-input v-model="itemBlock.content" maxlength="500"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-for="(itemOption,indexOption) in itemBlock.optionList" :key="indexOption">
                                    <el-col :span="20">
                                        <!-- 选项 -->
                                        <el-form-item :label="$t('salesManage.option')+(indexOption+1)" class="is-required">
                                            <el-input v-model="itemOption.content" maxlength="200"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="4" v-if="indexOption==itemBlock.optionList.length-1">
                                        <i class="el-icon-circle-plus-outline icon-add" @click="addOptionState(indexBlock)"></i>
                                        <i class="el-icon-remove-outline  icon-delete" @click="deleteOptionState(indexBlock)" v-if="itemBlock.optionList.length!==1"></i>
                                    </el-col>
                                </el-row>
                            </div>
                            <!-- 【单选】end -->
                            <!-- 【多选】start -->
                            <div v-if="itemBlock.questionType==2">
                                <el-form-item :label="'【'+$t('salesManage.multipleSelection')+'】'" :label-width="formLabelWidth">
                                    <el-radio-group v-model="itemBlock.isMust">
                                        <!-- 必填 -->
                                        <el-radio :label="1">{{$t('salesManage.required')}}</el-radio>
                                        <!-- 选填 -->
                                        <el-radio :label="2">{{$t('salesManage.optional')}}</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-row>
                                    <el-col :span="20">
                                        <el-form-item :label="$t('salesManage.problem')" class="is-required">
                                            <el-input v-model="itemBlock.content" maxlength="500"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row v-for="(itemOption,indexOption) in itemBlock.optionList" :key="indexOption">
                                    <el-col :span="20">
                                        <el-form-item :label="$t('salesManage.option')+(indexOption+1)" class="is-required">
                                            <el-input v-model="itemOption.content" maxlength="200"></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="4" v-if="indexOption==itemBlock.optionList.length-1">
                                        <i class="el-icon-circle-plus-outline icon-add" @click="addOptionState(indexBlock)"></i>
                                        <i class="el-icon-remove-outline  icon-delete" @click="deleteOptionState(indexBlock)" v-if="itemBlock.optionList.length!==1"></i>
                                    </el-col>
                                </el-row>
                            </div>
                            <!-- 【多选】end -->
                            <!-- 【输入】start -->
                            <div v-if="itemBlock.questionType==3">
                                <el-form-item :label="'【'+$t('salesManage.input')+'】'" :label-width="formLabelWidth">
                                    <el-radio-group v-model="itemBlock.isMust">
                                        <!-- 必填 -->
                                        <el-radio :label="1">{{$t('salesManage.required')}}</el-radio>
                                        <!-- 选填 -->
                                        <el-radio :label="2">{{$t('salesManage.optional')}}</el-radio>
                                    </el-radio-group>
                                </el-form-item>
                                <el-row>
                                    <el-col :span="20">
                                        <!-- 问题 -->
                                        <el-form-item :label="$t('salesManage.problem')" class="is-required">
                                            <el-input v-model="itemBlock.content" maxlength="500"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </div>
                            <!-- 【输入】end -->
                        </div>
                    </div>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="alertDialogVisible.templateEdit = false">{{$t('common.cancel')}}</el-button>
                <el-button type="primary" @click="submtEditingTempalte">{{$t('common.submit')}}</el-button>
            </span>
        </el-dialog>
        <!-- 编辑话术弹窗end -->

        <!-- 新增模板弹窗start -->
        <el-dialog :title="this.$t('salesManage.templateAdd')" :visible.sync="alertDialogVisible.templateAdd" width="500px">
            <!-- <div> -->
            <el-form :model="templateAddForm" :rules="templateAddFormRules" ref="templateAddForm" size="mini" label-width="100px">
                <el-form-item :label="$t('salesManage.templateSelect')+':'" :label-width="formLabelWidth" prop="templateType">
                    <el-select v-model="templateAddForm.templateType" :placeholder="$t('verify.plsChoose')" clearable>
                        <el-option
                                v-for="opt in templateList"
                                :label="opt.name"
                                :key="opt.id"
                                :value="opt.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item :label="$t('salesManage.nameTemplate')+':'" :label-width="formLabelWidth" prop="name">
                    <el-input v-model="templateAddForm.name" auto-complete="off" :placeholder="$t('verify.plsInput')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('salesManage.descriptionTemplate')+':'" :label-width="formLabelWidth" prop="remark">
                    <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" :placeholder="$t('verify.underXWords',{x: 200})" v-model="templateAddForm.remark" :maxlength="200">
                    </el-input>
                </el-form-item>

                <el-form-item :label="$t('salesManage.plsQuestionType')+':'" :label-width="formLabelWidth">
                    <!-- 单选 多选 输入 -->
                    <el-button type="text" @click="addEditState(1)" size="medium" style="paddingTop:7px">{{$t('salesManage.singleChoice')}}</el-button>
                    <el-button type="text" @click="addEditState(2)" size="medium" style="paddingTop:7px">{{$t('salesManage.multipleSelection')}}</el-button>
                    <el-button type="text" @click="addEditState(3)" size="medium" style="paddingTop:7px">{{$t('salesManage.input')}}</el-button>
                </el-form-item>

                <!-- 编辑话术问题块start -->
                <div class="editingStatement" ref="editingStatementWrap">
                    <div v-for="(itemBlock,indexBlock) in editingStatementObj.list" :key="indexBlock" class="editingStatementBlock">
                        <i class="el-icon-close icon-close" @click="deleteOptionBlock(indexBlock)"></i>
                        <!-- 【单选】start -->
                        <div v-if="itemBlock.questionType==1">
                            <el-form-item :label="'【'+$t('salesManage.singleChoice')+'】'" :label-width="formLabelWidth">
                                <el-radio-group v-model="itemBlock.isMust">
                                    <!-- 必填 -->
                                    <el-radio :label="1">{{$t('salesManage.required')}}</el-radio>
                                    <!-- 选填 -->
                                    <el-radio :label="2">{{$t('salesManage.optional')}}</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-row>
                                <el-col :span="20">
                                    <!-- 问题 -->
                                    <el-form-item :label="$t('salesManage.problem')" class="is-required">
                                        <el-input v-model="itemBlock.content" maxlength="500"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row v-for="(itemOption,indexOption) in itemBlock.optionList" :key="indexOption">
                                <el-col :span="20">
                                    <!-- 选项 -->
                                    <el-form-item :label="$t('salesManage.option')+(indexOption+1)" class="is-required">
                                        <el-input v-model="itemOption.content" maxlength="200"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="4" v-if="indexOption==itemBlock.optionList.length-1">
                                    <i class="el-icon-circle-plus-outline icon-add" @click="addOptionState(indexBlock)"></i>
                                    <i class="el-icon-remove-outline  icon-delete" @click="deleteOptionState(indexBlock)" v-if="itemBlock.optionList.length!==1"></i>
                                </el-col>
                            </el-row>
                        </div>
                        <!-- 【单选】end -->
                        <!-- 【多选】start -->
                        <div v-if="itemBlock.questionType==2">
                            <el-form-item :label="'【'+$t('salesManage.multipleSelection')+'】'" :label-width="formLabelWidth">
                                <el-radio-group v-model="itemBlock.isMust">
                                    <!-- 必填 -->
                                    <el-radio :label="1">{{$t('salesManage.required')}}</el-radio>
                                    <!-- 选填 -->
                                    <el-radio :label="2">{{$t('salesManage.optional')}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-row>
                                <el-col :span="20">
                                    <el-form-item :label="$t('salesManage.problem')" class="is-required">
                                        <el-input v-model="itemBlock.content" maxlength="500"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row v-for="(itemOption,indexOption) in itemBlock.optionList" :key="indexOption">
                                <el-col :span="20">
                                    <el-form-item :label="$t('salesManage.option')+(indexOption+1)" class="is-required">
                                        <el-input v-model="itemOption.content" maxlength="200"></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="4" v-if="indexOption==itemBlock.optionList.length-1">
                                    <i class="el-icon-circle-plus-outline icon-add" @click="addOptionState(indexBlock)"></i>
                                    <i class="el-icon-remove-outline  icon-delete" @click="deleteOptionState(indexBlock)" v-if="itemBlock.optionList.length!==1"></i>
                                </el-col>
                            </el-row>
                        </div>
                        <!-- 【多选】end -->
                        <!-- 【输入】start -->
                        <div v-if="itemBlock.questionType==3">
                            <el-form-item :label="'【'+$t('salesManage.input')+'】'" :label-width="formLabelWidth">
                                <el-radio-group v-model="itemBlock.isMust">
                                    <!-- 必填 -->
                                    <el-radio :label="1">{{$t('salesManage.required')}}</el-radio>
                                    <!-- 选填 -->
                                    <el-radio :label="2">{{$t('salesManage.optional')}}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <el-row>
                                <el-col :span="20">
                                    <!-- 问题 -->
                                    <el-form-item :label="$t('salesManage.problem')" class="is-required">
                                        <el-input v-model="itemBlock.content" maxlength="500"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </div>
                        <!-- 【输入】end -->
                    </div>
                </div>
            </el-form>
            <!-- </div> -->
            <div slot="footer" class="dialog-footer">
                <el-button @click="alertDialogVisible.templateAdd = false">{{ $t('common.cancel') }}</el-button>
                <el-button type="primary" @click="submitAddTm">{{$t('common.submit')}}</el-button>
            </div>
        </el-dialog>
        <!-- 新增模板弹窗end -->

    </div>
</template>

<script>
    import Pagination from '@/components/pagination';
    import mixin from '@/service/mixin';
    import alertDialog from '@/components/alert-dialog';
    import urlType from '@/api/url-type';
    import urlUtils from '@/libs/urlutils';
    import {apiConf} from '@/config/index';

    let that = null;
    export default {
        name: 'telemarketing-discourseManage',
        components: {
            Pagination,
            alertDialog
        },
        mixins: [mixin],
        data() {
            return {
                uploadUrl: `${apiConf.baseUrl}${urlType.telSales.importTmUserBatch}`,
                // uploadUrl: `${urlType.telSales.importTmUserBatch}`,
                headersParam: {
                    token: this.$storage.get('user').token
                },
                formLabelWidth: this.$i18n.locale === 'zhCN' ? '120px' : '200px',
                alertDialogVisible: {
                    templateAdd: false, // 新增模板
                    templateEdit: false // 编辑话述
                },
                alertDialogMsg: {},
                form: {
                    name: '',
                },
                templateEditForm: {
                    questionnaireTemplate: {
                        name: '',
                        id: '',
                        remark: '',
                    }
                },
                templateAddForm: {
                    templateType: '',
                    name: '',
                    remark: '',
                },
                templateAddFormRules: {
                    // templateType: [{ required: true, message: this.$t('audit.plsChoose'), trigger: 'blur' }],
                    name: [
                        { required: true, message: this.$t('verify.plsInput'), pattern: '[^ \x22]+', trigger: 'blur' },
                    ],
                },
                templateEditFormRules: {
                    questionnaireTemplate: {
                        name: [{ required: true, message: this.$t('verify.plsInput'),  pattern: '[^ \x22]+', trigger: 'blur' }],
                    }
                },
                editingStatementObj: {
                    list: [
                        // {
                        //   questionType: 1,
                        //   isMust:1,
                        //   content: '',
                        //   list: [{ content: '' },{ content: '' }]
                        // },
                        // {
                        //   questionType: 2,
                        //   isMust:2,
                        //   content: '',
                        //   list: [{ content: "453" }]
                        // },

                        // {
                        //   questionType: 3,
                        //   isMust:2,
                        //   content: '',
                        //   list: [{ content: "453" }]
                        // }
                    ]
                },
                tableData: [],
                ruleForm: [],
                rules: {},
                templateList: [], // 模板选择
            };
        },
        methods: {
            // 编辑模板确认,并提交数据
            confirmEditingTempalte(EditingStatementObj) {
                const params = {
                    questionnaireTemplate: {
                        id: '',
                        name: '',
                        remark: '',
                    },
                    questionList: []
                };
                params.questionnaireTemplate = this.templateEditForm.questionnaireTemplate;
                params.questionList = this.editingStatementObj.list;
                this.$api.telSales.updateTemplate(params).then((res) => {
                    const { status, error, msg } = res;
                    if (status === '1' && error === '00000000') {
                        this.$message.success(this.$t('common.successfulOperation'));
                        this.alertDialogVisible.templateEdit = false;
                        this.getTableData();
                    } else {
                        this.$message({
                            type: 'error',
                            message: msg
                        });
                    }
                });
            },
            // 编辑模板确认
            submtEditingTempalte() {
                this.$refs.templateEditForm.validate((valid) => {
                    if (valid) {
                        if (this.editingStatementObj.list.length < 1) { // 问题类型为必选
                            this.$message.error(this.$t('salesManage.plsQuestionType'));
                            return;
                        }
                        let flagEditingStatementObj=true;

                        this.editingStatementObj.list.forEach((currentValue, currentIndex, arr)=>{
                            if(currentValue.content!==''){
                                if(currentValue.questionType===2||currentValue.questionType===1){
                                    currentValue.optionList.forEach((currentValue2, currentIndex2, arr2)=>{
                                        if(currentValue2.content===''){
                                            flagEditingStatementObj=false;
                                        }
                                    });
                                }
                            }else{
                                flagEditingStatementObj=false;
                            }
                        });
                        if(!flagEditingStatementObj){
                            this.$message.error(this.$t('salesManage.requiredFields'));
                            return false;
                        }

                        let templ = '';
                        if (this.templateEditForm.useBatch) {
                            templ = `<p>${this.$t('salesManage.batchNumber')}: <span>${this.templateEditForm.useBatch}</span></p><p>${this.$t('salesManage.tipsEditTemplate')} </p>`;
                        } else {
                            templ = `<p>${this.$t('salesManage.batchNumber')}: <span>--</span></p><p>${this.$t('salesManage.tipsEditTemplate')} </p>`;
                        }
                        this.$confirm(templ, this.$t('salesManage.confirmEditTemplate'), {
                            confirmButtonText: this.$t('common.confirm'),
                            cancelButtonText: this.$t('common.cancel'),
                            dangerouslyUseHTMLString: true
                        }).then(() => {
                            this.confirmEditingTempalte(this.editingStatementObj);
                        }).catch(() => {
                        });

                    } else {
                        return false;
                    }
                });
            },
            addEditState(type) {
                switch (type) {
                    case 1:
                        this.editingStatementObj.list.push({
                            questionType: 1,
                            isMust: 1,
                            content: '',
                            optionList: [{ content: '' }]
                        });
                        break;
                    case 2:
                        this.editingStatementObj.list.push({
                            questionType: 2,
                            isMust: 1,
                            content: '',
                            optionList: [{ content: '' }]
                        });
                        break;
                    case 3:
                        this.editingStatementObj.list.push({
                            questionType: 3,
                            isMust: 1,
                            content: '',
                            optionList: [{ content: '' }]
                        });
                        break;
                    default:
                        break;
                }
                const ele = this.$refs.editingStatementWrap;
                this.$nextTick(() => {
                    ele.scrollTop = ele.scrollHeight;
                });
            },
            addOptionState(indexBlock) {
                this.editingStatementObj.list[indexBlock].optionList.push({ content: '' });
            },
            deleteOptionState(indexBlock) {
                this.editingStatementObj.list[indexBlock].optionList.pop({ content: '' });
            },
            deleteOptionBlock(indexBlock) {
                this.editingStatementObj.list.splice(indexBlock, 1);
            },
            // 编辑模板
            editingTemplate(row) {

                this.templateEditForm = {
                    questionnaireTemplate: {
                        name: row.name,
                        id: row.id,
                        remark: row.remark,
                    },
                    questionList: [],
                    useBatch: row.useBatch
                };
                const params = {
                    id: row.id,
                    // importId:row.id
                };
                this.$api.telSales.getTemplate(params).then((res) => {
                    const { status, data, error } = res;
                    if (status === '1' && error === '00000000') {
                        // this.editingStatementObj.list = data.questionList;
                        data.questionList.forEach((itemOne) => {
                            itemOne.optionList = data.optionList.filter(itemTwo => itemTwo.questionId === itemOne.id);
                        });

                        this.editingStatementObj.list = data.questionList;
                    }
                });
                this.alertDialogVisible.templateEdit = true;
                // 清楚上一个的验证，以及表单数据
                this.$nextTick(() => {
                    this.$refs.templateEditForm.clearValidate();
                });
            },
            // 分配
            distribution(row) {
                const params = {
                    batchId: row.batchId,
                    importId: row.id
                };
                this.$api.telSales.distributionUser(params).then((res) => {
                    const { status, error } = res;
                    if (status === '1' && error === '00000000') {
                        this.$message({
                            type: 'success',
                            message: this.$t('salesManage.allotSucc')
                        });
                        this.getTableData();
                    } else {
                        this.$alert(this.$t('salesManage.failAllocation'), this.$t('salesManage.confirmAllocation'), {
                            confirmButtonText: this.$t('common.confirm'),
                        });
                    }
                });
            },
            // 删除模板
            deleteTemplate (row) {
                this.$confirm(this.$t('system.isConfirmDelete'), this.$t('salesManage.tips'), {
                    confirmButtonText: this.$t('common.confirm'),
                    cancelButtonText: this.$t('common.cancel')
                    // type: 'warning'
                })
                    .then(() => {
                        this.deleteTemplateConfirm(row);
                    })
                    .catch(() => {
                        // this.$message({
                        //   type: 'info',
                        //   message: '已取消回收'
                        // });
                    });
            },
            // 删除模板确认
            deleteTemplateConfirm(row) {
                const params = {
                    id: row.id
                };
                this.$api.telSales.deleteTemplate(params).then((res) => {
                    const { status, data, error } = res;
                    if (status === '1' && error === '00000000') {
                        this.$message.success(this.$t('common.successfulOperation'));
                        this.getTableData();
                    }
                });
            },
            // 导出话述
            exportStatement(row) {
                const params = {importId: row.id};
                const user = this.$storage.get('user');
                const language = this.$storage.getLocal('language');
                params.token = user.token;
                params.language = language;
                params.Authorization = 'Basic cGluamFtYW5nbzpwaW5qYW1hbmdvMDE4';
                const {$apiConf} = this;
                const url = this.$urlUtil.fillParams(params, $apiConf.baseUrl + $apiConf.urlType.telSales.exportTmUserBatch, ['page']);
                this.$openNewBlank(url);
            },
            search() {
                this.$refs.form.validate((valid) => {
                    if (valid) {
                        this.getTableData({ currentPage: 1 }, this.form);
                    } else {
                        this.$message.error(this.$t("verify.plsCheckFilters"));
                    }
                });
            },
            clear() {
                const { form } = this.$refs;
                if (form) {
                    form.resetFields();
                }
            },
            submitAddTm() {
                this.$refs.templateAddForm.validate((valid) => {
                    if (valid) {
                        if (this.editingStatementObj.list.length < 1) { // 问题类型为必选
                            this.$message.error(this.$t('salesManage.plsQuestionType'));
                            return;
                        }
                        let flagEditingStatementObj=true;

                        this.editingStatementObj.list.forEach((currentValue, currentIndex, arr)=>{
                            if(currentValue.content!==''){
                                if(currentValue.questionType===2||currentValue.questionType===1){
                                    currentValue.optionList.forEach((currentValue2, currentIndex2, arr2)=>{
                                        if(currentValue2.content===''){
                                            flagEditingStatementObj=false;
                                        }
                                    });
                                }
                            }else{
                                flagEditingStatementObj=false;
                            }
                        });
                        if(!flagEditingStatementObj){
                            this.$message.error(this.$t('salesManage.requiredFields'));
                            return false;
                        }
                        const params = {
                            questionnaireTemplate: {
                                name: '',
                                remark: '',
                                number: ''
                            },
                            questionList: []
                        };
                        const opts = this.templateAddForm;
                        Object.keys(opts).forEach((key) => {
                            if (typeof opts[key] !== 'undefined' || params.questionnaireTemplate[key]) {
                                params.questionnaireTemplate[key] = opts[key];
                            }
                        });
                        params.questionList = this.editingStatementObj.list;
                        params.questionnaireTemplate.number = this.editingStatementObj.list.length;
                        this.$api.telSales.insertTm(params).then((res) => {
                            const { status, error } = res;
                            if (status === '1' && error === '00000000') {
                                this.$message.success(this.$t('common.successfulOperation'));
                                this.alertDialogVisible.templateAdd = false;
                                this.getTableData();
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            templateAdd (row) {
                this.$api.telSales.listTm({}).then((res) => {
                    const { status, data, error } = res;
                    if (status === '1' && error === '00000000') {
                        this.templateList = data || [];
                        this.templateList.splice(0, 0, { 'id': '', 'name': this.$t('salesManage.templateAdd') });  // 新增模板
                    }
                });
                this.alertDialogVisible.templateAdd = true;
                // 清楚上一个的验证，以及表单数据
                this.$nextTick(() => {
                    this.$refs.templateAddForm.resetFields();
                    this.editingStatementObj.list = [];
                });
            },
            getTableData (page = this.page, opts = this.form) {
                const params = this.handleParams(page, opts);
                this.$api.telSales.listPage(params).then((res) => {
                    const { status, data, error } = res;
                    if (status === '1' && error === '00000000') {
                        this.tableData = data.list || [];
                        // this.setPage(data.page, this.page);
                        this.setPage({
                            pageNo: data.pageNum,
                            pageSize: data.pageSize,
                            totalRecord: data.total,
                            totalPage: data.pages
                        }, this.page);
                    }
                });
            },
            handleParams(page = this.page, opts = this.form) {
                const params = {
                    name: '',
                    page: {
                        pageNo: page.currentPage,
                        pageSize: this.page.pageSize
                    }
                };

                if (opts) {
                    Object.keys(params).forEach((key) => {
                        if (typeof opts[key] !== 'undefined') {
                            params[key] = opts[key];
                        }
                    });
                }
                return params;
            },
        },
        computed: {},
        filters: {
            currentStatus(type) {
                // 当前状态：0 待分配  1 已分配  2 已回收
                switch (type) {
                    case 0:
                        return that.$t('tel.waitAssign');
                    case 1:
                        return that.$t('salesManage.assigned');
                    case 2:
                        return that.$t('salesManage.recycled');
                    default:
                        return '';
                }
            }
        },
        created() {
            that = this;
            this.getTableData();
            this.tableMaxHeight = window.document.body.clientHeight - 200;
        },
        watch: {
            'templateAddForm.templateType': function (val) {
                if (val === '') {
                    this.editingStatementObj.list = [];
                } else {
                    this.$api.telSales.getTemplate({id: val}).then((res) => {
                        const {status, data, error} = res;
                        if (status === '1' && error === '00000000') {
                            data.questionList.forEach((itemOne) => {
                                itemOne.optionList = data.optionList.filter(itemTwo => itemTwo.questionId === itemOne.id);
                            });

                            this.editingStatementObj.list = data.questionList;
                        }
                    });
                }
            }
        }
    };
</script>

<style lang='scss' scoped>
    .search-input {
        width: 100%;
    }

    // 编辑话术弹窗
    .editingStatement {
        max-height: 400px;
        overflow: auto;
        .editingStatementBlock {
            background-color: #f0f0f0;
            position: relative;
            padding: 20px 0 0;
            margin: 10px auto;
            position: relative;
        }
    }

    .el-button + .el-button {
        margin-left: 10px;
    }

    .icon-add, .icon-delete, icon-close {
        font-size: 26px;
        margin-left: 5px;
        cursor: pointer;
    }

    .icon-add {
        color: #52a0db;
    }

    .icon-delete {
        color: #ff0000;
    }

    .icon-close {
        position: absolute;
        right: 10px;
        top: 10px;
    }

    .popper-word-break {
        max-width: 300px;
        word-break: keep-all;
        word-break: break-all;
        background-color: #fff;
        color: #000;
    }

    .btn_red {
        color: #d9415c;
    }

    // .mr5{margin-right: 15px;}
</style>
<style lang="scss">
    [data-page=telemarketing-discourseManage] {
        .el-col {
            padding-left: 10px;
        }
        .el-table .cell, .el-table th > .cell {
            word-break: keep-all;
            word-wrap: break-word;
        }
        .el-button {
            margin-bottom: 18px
        }
        .el-table__row {
            .el-button {
                margin-bottom: 0px
            }
        }
    }
</style>

